import time
import cv2
from queue import Queue
from threading import Thread
import os
import numpy as np
############################
import logging
my_normal_logger = logging.getLogger('django')
############################

# 保持摄像头长连接 用列队 防止获取图片变花
class Camera:
    def __init__(self, device_id, frames_len=5, acc=1):
        self.device_id = device_id
        # self.cam = cv2.VideoCapture(self.device_id, cv2.CAP_DSHOW)  # 本地摄像头使用
        self.cam = cv2.VideoCapture(self.device_id)  # 网络IP摄像头使用

        self.frames_len = frames_len
        self.frame_queue = Queue(self.frames_len)  # 帧队列
        self.acc = acc
        self.is_running = False  # 状态标签
        self.is_sleep = True
        self._data = {}

    def capture_queue(self):
        # capture picture
        cnt = 0
        my_normal_logger.info('self.cam.isOpened() -->' + str(self.cam.isOpened()))
        while self.is_running and self.cam.isOpened():
            ret = self.cam.grab()
            if not ret:
                continue

            if self.is_sleep:
                cnt = 0
                continue

            cnt += 1
            if cnt % self.acc == 0:
                ret, frame = self.cam.retrieve()

                if self.frame_queue.qsize() >= self.frames_len:
                    self.frame_queue.get()
                self._data["image"] = frame.copy()
                self.frame_queue.put(self._data)

    def run(self):
        my_normal_logger.info('thread_capture  capture_queue  running')
        self.is_running = True
        self.thread_capture = Thread(target=self.capture_queue)
        self.thread_capture.daemon = True
        self.thread_capture.start()

    def stop(self):
        my_normal_logger.info('thread_capture  capture_queue  stop')
        self.is_running = False
        self.cam.release()
